<template>
  <div>
    <my-tabs :tab-list="tabList">
      <el-button slot="right" type="primary" size="mini" @click="openAddressModify"
        >新增收货地址</el-button
      >
    </my-tabs>
    <div class="address-item " v-for="(item, index) in addressList" :key="index">
      <div class="other">
        <div class="name">{{ item.consignee }}</div>
        <div class="default" v-if="item.default == 1">
          默认地址
        </div>
        <div class="prominent">
          <el-link type="info" :underline="false" @click.stop="handleAddressDelete(item.id)"
            >删除</el-link
          >
          <el-link type="primary" :underline="false" @click.stop="openAddressModify(item)"
            >修改</el-link
          >
          <el-link
            type="primary"
            :underline="false"
            v-if="item.default == 0"
            @click.stop="handleAddressDefault(item.id)"
            >设为默认</el-link
          >
        </div>
      </div>
      <div class="line"></div>
      <div class="phone">{{ item.phone }}</div>
      <div class="location">
        <i class="el-icon-location-outline el-icon--left"></i>
        <span class="bold">{{ item.areatext }}</span>
        {{ item.address }}
      </div>
    </div>

    <el-dialog
      :title="`${updateAddress ? '修改' : '新增'}收货地址`"
      v-if="editorAddressVisible"
      :visible="editorAddressVisible"
      width="530px"
      :close-on-click-modal="false"
      :before-close="closeAddressModify"
      custom-class="address-dialog"
    >
      <el-form
        ref="addressForm"
        :rules="addressFormRules"
        :model="addressForm"
        label-width="85px"
        size="mini"
      >
        <el-form-item label="收货人姓名" prop="consignee">
          <el-input v-model="addressForm.consignee" placeholder="请填写收货人姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请填写收货人手机号"></el-input>
        </el-form-item>
        <el-form-item label="所在地区" prop="areacode">
          <el-cascader
            ref="region"
            v-model="addressForm.areacode"
            :options="addressData"
            placeholder="请选择地区"
            value="code"
            label="name"
            :props="{ value: 'code', label: 'name' }"
            @change="handleRegionChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="addressForm.address"
            :minlength="1"
            :maxlength="100"
            :showWordLimit="true"
            placeholder="请输入详细地址"
          ></el-input>
        </el-form-item>
        <el-form-item prop="default">
          <el-checkbox v-model="addressForm.default" :true-label="1" :false-label="0"
            >设为默认地址</el-checkbox
          >
        </el-form-item>
        <div class="el-row--flex is-justify-center ">
          <el-button size="mini" @click="closeAddressModify">取消</el-button>
          <el-button
            type="primary"
            size="mini"
            :disabled="disabled"
            @click="submitAddressForm('addressForm')"
            >保存</el-button
          >
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import MyTabs from '../components/myTab.vue'
import addressData from '@/utils/Area.json'
const defaultValueRef = () => ({
  consignee: '',
  phone: '',
  areacode: [],
  areatext: '',
  address: '',
  default: 0
})
export default {
  components: {
    MyTabs
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号'))
      } else if (!this.$util.mobile(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    return {
      tabList: [
        {
          title: '收货地址'
        }
      ],
      addressData, // 地址数据
      defaultAddress: 0, // 默认地址id
      currentAddress: 0, // 当前选择的地址id
      updateAddress: 0, // 修改地址id
      addressVisible: false, // 地址展开可见性
      editorAddressVisible: false, // 编辑地址可见性
      addressList: [], // 地址列表
      addressForm: defaultValueRef(),
      disabled: false,
      addressFormRules: {
        consignee: [
          {
            required: true,
            min: 1,
            message: '请填写正确收货人姓名',
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            trigger: 'blur',
            validator: validatePhone
          }
        ],
        areacode: [
          {
            type: 'array',
            required: true,
            message: '请选择地区',
            trigger: 'change'
          }
        ],
        address: [
          {
            required: true,
            min: 1,
            message: '请输入详细地址',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    // 获取地址列表
    getAddressList() {
      this.$api.getMallAddressList(res => {
        const { data } = res
        this.addressList = data
      })
    },
    // 删除
    handleAddressDelete(id) {
      this.$messageBox
        .confirm('您确定要删除该收货地址吗？', {
          title: '删除收货人信息'
        })
        .then(() => {
          this.$api.deleteMallAddress(
            {
              id: id
            },
            res => {
              this.$message.success(res.msg)
              // 更新地址列表
              this.getAddressList()
            }
          )
        })
        .catch(() => {})
    },
    // 默认
    handleAddressDefault(id) {
      this.$api.updateMallAddressDefault(
        {
          id: id,
          default: 1
        },
        res => {
          this.$message.success(res.msg)
          // 更新地址列表
          this.getAddressList()
        }
      )
    },
    // 地区选择
    handleRegionChange() {
      let text = this.$refs['region'].getCheckedNodes()[0].pathLabels
      this.addressForm.areatext = text.join(' ')
    },
    // 打开编辑地址
    openAddressModify(item) {
      this.editorAddressVisible = true
      if (item.id) {
        this.updateAddress = item.id
        this.addressForm.consignee = item.consignee
        this.addressForm.phone = item.phone
        this.addressForm.areacode = item.areacode
        this.addressForm.areatext = item.areatext
        this.addressForm.address = item.address
        this.addressForm.default = item.default
      } else {
        this.updateAddress = 0
        Object.assign(this.addressForm, defaultValueRef())
      }
    },
    // 关闭编辑地址
    closeAddressModify() {
      this.editorAddressVisible = false
      this.$refs['addressForm'].resetFields()
    },
    // 修改/编辑地址
    submitAddressForm() {
      this.$refs['addressForm'].validate(valid => {
        if (valid) {
          this.disabled = true
          this.addressForm.areacode = this.addressForm.areacode.toString()
          // 修改地址
          if (this.updateAddress) {
            let params = {
              ...this.addressForm,
              id: this.updateAddress
            }
            this.$api.updateMallAddress(params, res => {
              this.closeAddressModify()
              this.$message.success(res.msg)
              // 更新地址列表
              this.getAddressList()
              setTimeout(() => {
                this.disabled = false
              }, 50)
            })
          } else {
            this.$api.addMallAddress(this.addressForm, res => {
              this.closeAddressModify()
              this.$message.success(res.msg)
              // 更新地址列表
              this.getAddressList()
              setTimeout(() => {
                this.disabled = false
              }, 50)
            })
          }
        } else {
          return false
        }
      })
    }
  },
  created() {
    this.getAddressList()
  }
}
</script>

<style lang="scss" scoped>
.address-item {
  position: relative;
  border: 1px solid #e4e7ed;
  box-sizing: border-box;
  margin-bottom: 20px;
  padding: 18px 20px;
  .other {
    display: flex;
    align-items: center;
    .default {
      margin-left: 10px;
      font-weight: 400;
      font-size: 12px;
      color: #ffffff;
      line-height: 18px;
      height: 18px;
      padding: 0 3px;
      @include edu-color-primary(background-color);
    }
    .el-link + .el-link {
      margin-left: 15px;
    }
    .prominent {
      opacity: 0;
      transition: opacity 0.2s;
      margin-left: auto;
      line-height: 1;
    }
  }
  .line {
    border: 1px dashed #e4e7ed;
    margin-top: 18px;
  }
  .name {
    max-width: 190px;
    font-size: 15px;
    color: $text-color-import;
    line-height: 1;
    color: #303133;
    @include ellipsis();
  }
  .phone {
    margin-top: 15px;
    font-size: 15px;
    font-weight: 500;
    line-height: 1;
    color: $text-color-import;
  }
  .location {
    display: flex;
    margin-top: 15px;
    font-size: 14px;
    line-height: 20px;
    font-weight: 500;
    color: $text-color-import;
    .el-icon-location-outline {
      margin-top: 2px;
    }
    .bold {
      font-weight: 600;
      margin-right: 5px;
    }
  }
  &:hover .prominent {
    opacity: 1;
  }
}

::v-deep .address-dialog {
  .el-dialog__header {
    border-bottom: 1px solid #e4e7ed;
  }
  .el-dialog__body {
    .el-form-item__label {
      font-size: 12px;
    }
    .el-input--mini .el-input__inner {
      height: 32px;
      line-height: 32px;
      border-radius: 0;
    }
    .el-button--mini {
      padding: 8px 20px;
    }
    .el-checkbox__inner {
      border-radius: 100%;
      display: block;
    }
    .el-checkbox__label {
      font-size: 13px;
      line-height: 16px;
    }
  }
}
</style>
